package com.example.fragmentpageradapter;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.example.fragmentpageradapter.adapter.ViewPagerAdapter;
import com.example.fragmentpageradapter.fragment.HomeFragment;
import com.example.fragmentpageradapter.fragment.ProfileFragment;
import com.google.android.material.tabs.TabLayout;

/**
 * viewPager 先拿到ViewPager对象 用于翻页(view)或者(Fragment)
 * 放里面添加Fragment对应和对应的标题就可
 */
public class MainActivity extends AppCompatActivity {

    private ViewPager viewPager;
    private TabLayout tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        viewPager = findViewById(R.id.viewPager);
        tabLayout = findViewById(R.id.tabLayout);
        // 设置 viewPager 与 fragment 联动
        setupViewPager(viewPager);
        // 设置tabLayout与viewPager联动
        tabLayout.setupWithViewPager(viewPager);

    }

    private void setupViewPager(ViewPager viewPager) {
        // 得到FragmentManager管理器
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager()
                , FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        adapter.addFragment(HomeFragment.newInstance(), "首页");
        adapter.addFragment(ProfileFragment.newInstance(), "设置");
        viewPager.setAdapter(adapter);
    }
}